<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\File;
use App\Models\Files;
use App\Transformers\FileTransformer;

class FilesController extends Controller
{
    public function store(Request $request, Files $files)
    {
    	$file = $request->file('file');
    	$type = $request->type;
    	
    	if(! in_array($type, ['vedio', 'audio', 'doc'])) {
    		return $this->response->array(['error' =>'不符合文件类型']);
    	}

    	$fileInfo = $this->upload_file($file, $type);

    	$files->fill($fileInfo);
    	$files->save();

    	return $this->response->item($files, new FileTransformer())->setStatusCode(201);
    }


    private function upload_file($file, $type)
    {
    	// 获取文件上传的后缀名
    	$file_extension = $file->getClientOriginalExtension();
    	// 获取文件名
    	$file_name = $file->getClientOriginalName();
    	// 获取文件上传大小
    	$file_size = $file->getClientSize();
    	// 获取缓存在 temp 目录下的文件名
    	$file_temp_name = $file->getFilename();
    	// 获取上传的文件缓存在 tmp 目录下的绝对文件路径
    	$file_tmp_path=$file->getRealPath();
    	// 获取文件 Mime 类型
    	$file_type = $file->getClientMimeType();

    	// 保存文件
    	// $file = $file->move('./uploads/file/'.date("Ym/d", time()), $file_name);
    	$upload = Storage::putFileAs($type, $file, $file_name);

    	$path = url('uploads/file') . '/' . $upload;

    	$fileInfo = [
    		'title' => $file_name,
    		'extension' => $file_extension,
    		'size' => $file_size,
    		'path' => $path,
    	];

    	return $fileInfo;
    }
}
